<?php

include('../../include/functions.inc.php');
if (!isEmpty(getParam('operation'))) {
    switch (getParam('operation')) {
        case 'refresh':
            loadCareer($db);
            break;
        case 'aiu':
            findStudent($db, 'AIU_CODE=' . getParam('AIU_CODE'));
            break;
        case 'id':
            findStudent($db, 'ID=' . getParam('ID'));
            break;
        case 's':
            save($db, $user);
            break;
        case 'prev':
            prevAssign($db, $user);
            break;
        case 'stud':
            listStudents();
            break;
    }
}

function findStudent($db, $where) {
    $r = $db->query_select("cllg_student", $where);
    if (count($r) > 0) {
        $c = $r[0];
        $datos = array('NAME' => $c['FIRTS_NAME'] . ',' . $c['LAST_NAME'], 'ID' =>
            $c['ID'], 'AIU' => ($c['AIU_CODE'] != NULL) ? $c['AIU_CODE'] : "");
        $_SESSION['pack'] = serialize($datos);
    } else {
        $datos = array('ERROR' => 'NO EXISTE NINGUN ESTUDIANTE CON ESE CODIGO!');
        $_SESSION['pack'] = serialize($datos);
    }
    header('Location: ../../include/transport.php');
}

function prevAssign($db, $user) {
    $student = getParam('ID') == NULL ? getParam('AIU_CODE') : getParam('ID');
    $prev = findStudentAssigns($db, $student, getParam('CARRERA'), $user, getParam('CYCLE'));
    $data = array('ST' => 1);
    if ($prev > 0) {
        $data = array('ST' => 0, 'ERROR' => 'El estudiante ya esta asignado a esta carrera y ciclo!');
    }
    $_SESSION['pack'] = serialize($data);
    header('Location: ../../include/transport.php');
}

function loadCareer($db) {
    $r = $db->query_select("cllg_charge_policy", "FK_CAREER=" . getParam('CARRERA'));
    $index = 0;
    $json_string = "[";
    foreach ($r as $c) {
        $json_string .= ($index == 0) ? "" : ",";
        $arr = array('CARGO' => $c['NAME'],
            'MONTO' => number_format($c['AMOUNT'], 2),
            'FRECUENCIA' => $c['FRECUENCY'],
            'DIA COBRO' => $c['DAY_APPLY'],
            'MES COBRO' => $c['MONTH_APPLY'],
            'NO.CARGOS' => $c['COUNT'],
            'MORA' => number_format($c['PENALTY'], 2));
        $json_string.= json_encode($arr);
        $index++;
    }
    $json_string.="]";
    $_SESSION['pack'] = serialize($json_string);
    header('Location: ../../include/transport.php?ready=true');
}

function listStudents() {
    header('Location: ../students/slistStudents.php');
}

function save($db, $user) {

    $student = getParam('ID') == NULL ? getParam('AIU_CODE') : getParam('ID');
    $selectedCycle = getParam('CYCLE');
    
    $strQuery = "SELECT  YEAR(date_begin) anio 
                FROM    cllg_college_cycle
                WHERE   cllg_college_cycle.code = " . sqlValue(getParam("CYCLE"), "int") . "
                AND     cllg_college_cycle.fk_entity = " . $user->entity;
    $arrInfoCiclo = $db->query_toArray($strQuery);
    $arrInfoCiclo = $arrInfoCiclo[0];
    
    
    $yearAssign = $arrInfoCiclo['anio'];
    $monthAssign = getParam("STARTMONTH");
    //asigna estudiante
    $db->query_insert('cllg_student_assign', array(
        'FK_STUDENT' => sqlValue($student, 'int'),
        'FK_ENTITY' => sqlValue($user->entity, 'int'),
        'STATUS' => 1,
        'FK_CYCLE' => sqlValue($selectedCycle, 'int'),
        'FK_CAREER' => sqlValue(getParam('CARRERA'), 'int'),
        'CREATED_BY' => sqlValue($user->name, 'text'),
        'CREATED' => sqlValue(date("Y-m-d"), 'date'),
        'START_DATE' => sqlValue(date('Y-m-d', strtotime(date("01-$monthAssign-$yearAssign"))), "date")));
    $course_code = array();
    $assign = mysql_insert_id();
    
    if( $assign > 0 ) {
        $strQuery ="SELECT  COUNT(cllg_student_assign.id) asignados 
                    FROM    cllg_student_assign
                    WHERE   cllg_student_assign.fk_cycle = " . sqlValue($selectedCycle, "int") . "
                    AND     cllg_student_assign.fk_entity = " . $user->entity . "
                    AND     cllg_student_assign.status = 1";
        $arrInfoEstudinateAsignacion = $db->query_toArray($strQuery);
        $intEstudinatesAsignados = $arrInfoEstudinateAsignacion[0];        
        $db->query_update("cllg_college_cycle", array("ACTIVE_STUDENTS" => $intEstudinatesAsignados['asignados']), "CODE=" . $selectedCycle . " AND FK_ENTITY=" . $user->entity);
    }

    foreach ($_GET as $key => $value) {
        $arrGet = explode('_', $key);
        if( $arrGet[0] == 'SECTION' && $arrGet[1] == 'course') {
            $course_code[$arrGet[3]] = $value;    
        }
    }

    foreach ($course_code as $code => $section) {
        $db->query_insert("cllg_assign_detail", array("FK_ASSIGN" => $assign,
            "FK_COURSE" => $code,
            "SECTION" => sqlValue($section, 'text')));
    }

    $rs = array();
    $rs = $db->query_select('cllg_account', 'FK_STUDENT=' . $student);
    if (count($rs) == 0) {//registra una nueva cuenta
        $db->query_insert('cllg_account', array(
            'FK_STUDENT' => sqlValue($student, 'int'),
            'STATUS' => 1,
            'CURR_BALANCE' => sqlValue("0", 'double'),
            'PREV_BALANCE' => sqlValue("0", 'double'),
            'FK_ENTITY_OWNER' => sqlValue($user->entity, 'int'),
            'CREATED_BY' => sqlValue($user->name, 'text'),
            'CREATED' => sqlValue(date("Y-m-d"), 'date')));
        $rs = $db->query_select('cllg_account', 'FK_STUDENT=' . $student);
    }
    $ac = $rs[0];
    $date = date('Y-m-d');
    $cargos = $db->query_select('cllg_charge_policy', 'FK_CAREER=' . getParam('CARRERA'));
    $startMonth = getParam("STARTMONTH");
    $cBalance = $ac['CURR_BALANCE'];
    $acum = 0;
    $desc = getParam('DISCOUNT') != NULL ? getParam('DISCOUNT') : 0;
    $startMonth = getParam("STARTMONTH") - 1;
    foreach ($cargos as $cargo) {
        $year = $arrInfoCiclo['anio'];
        $month = $cargo["MONTH_APPLY"] + $startMonth;
        $day = $cargo["DAY_APPLY"];
        $count = $cargo["COUNT"];
        $moneda = isset($cargo["MONEDA"]) ? $cargo["MONEDA"] : 1;

        if ($month >= 13 && $month <= 24) {
            $year = $year + 1;
            $month = $month - 12;
        } else if ($month >= 25 && $month <= 36) {
            $year = $year + 2;
            $month = $month - 24;
        } else if ($month >= 37 && $month <= 48) {
            $year = $year + 3;
            $month = $month - 36;
        }

        for ($i = 0; $i < $count; $i++) {
            $monto = $cargo['AMOUNT'];
            $acum += $monto;
            $pBalance = $cBalance;
            $cBalance += $cargo['AMOUNT'];

            $dateLimit = date('Y-m-d', strtotime(date("$day-$month-$year")));
            $nameMonth = date('M', strtotime(date("$day-$month-$year")));

            $db->query_insert("cllg_cargo", array(
                "FK_ACCOUNT" => sqlValue($ac['ID'], 'int'),
                "DATE_LIMIT" => sqlValue($dateLimit, 'date'),
                "PENALTY" => sqlValue($cargo['PENALTY'], 'double'),
                "DESCRIPTION" => sqlValue($cargo['NAME'] . " de " . $nameMonth, 'text'),
                "CREATED" => sqlValue($date, 'date'),
                "CREATED_BY" => sqlValue($user->name, 'text'),
                "AMOUNT" => sqlValue($cargo['AMOUNT'], 'double'),
                "PREV_BALANCE" => sqlValue($pBalance, 'double'),
                "CURR_BALANCE" => sqlValue($cBalance, 'double'),
                "MONEDA" => $moneda,
                "FK_STUDENT_ASSIGN" => $assign));

            if ($cargo["FRECUENCY"] == 1) {
                $month = $month + 1;
            } else if ($cargo["FRECUENCY"] == 2) {
                $month = $month + 2;
            } else if ($cargo["FRECUENCY"] == 3) {
                $month = $month + 3;
            } else if ($cargo["FRECUENCY"] == 4) {
                $month = $month + 4;
            } else if ($cargo["FRECUENCY"] == 5) {
                $month = $month + 5;
            } else if ($cargo["FRECUENCY"] == 6) {
                $month = $month + 6;
            } else if ($cargo["FRECUENCY"] == 12) {
                $month = $month + 12;
            }

            if ($month > 12) {
                $dif = $month - 12;
                $month = ($dif == 0 ? 1 : $dif);
                $year++;
            }
        }
    }

    $db->query_update('cllg_account', array('CURR_BALANCE' => $acum + $ac['CURR_BALANCE'],
        'PREV_BALANCE' => $ac['CURR_BALANCE']), 'ID=' . $ac['ID']);
    $msj = '<div style="width:100%; background:FFFFCC; border:1px solid red; text-align:center;">Alumno Asignado Exitosamente</div>';

    //exit();
    echo '<script>
			window.location.href="res.php?asigned=' . $assign . '"			
		  </script>
		  ';
}

?>